package com.bizmda.bizsip.sample.app.service;

import com.bizmda.bizsip.app.api.AppClientFactory;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizResultEnum;
import com.bizmda.bizsip.sample.sink.api.AccountDTO;
import com.bizmda.bizsip.sample.sink.api.CustomerDTO;
import com.bizmda.bizsip.sample.sink.api.Sample16Interface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author shizhengye
 */
@Service
@Slf4j
public class Sample16AppService implements Sample16Interface {
    private final Sample16Interface sinkInterface =  AppClientFactory.getSinkClient(Sample16Interface.class,"sample16-sink");
    int retryNum = 0;

    @Override
    public String doService1(String arg1) {
        return this.sinkInterface.doService1(arg1);
    }

    @Override
    public void doService2(String arg1, int arg2) {
        this.sinkInterface.doService2(arg1,arg2);
    }

    @Override
    public String doService1Exception(String arg1) throws BizException {
        return this.sinkInterface.doService1Exception(arg1);
    }

    @Override
    public CustomerDTO queryCustomerDTO(String customerId) {
        return this.sinkInterface.queryCustomerDTO(customerId);
    }

    @Override
    public AccountDTO[] queryAccounts(AccountDTO accountDTO) {
        return this.sinkInterface.queryAccounts(accountDTO);
    }

    @Override
    public List<AccountDTO> queryAccountList(AccountDTO accountDTO) {
        return this.sinkInterface.queryAccountList(accountDTO);
    }

    @Override
    public String notify(int maxRetryNum,String result) throws BizException {
        log.info("收到消息: {},{}", maxRetryNum,result);
        try {
            log.info("retryNum:{},休眠1000ms...",this.retryNum);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
        if (retryNum >= maxRetryNum) {
            this.retryNum = 0;
            if ("success".equalsIgnoreCase(result)) {
                log.info("成功返回响应!");
                return "成功返回响应!";
            }
            else {
                log.info("返回其它异常错误!");
                throw new BizException(BizResultEnum.OTHER_ERROR);
            }
        }
        this.retryNum ++;
        log.info("返回响应超时错误,等待下一次重试...");
        throw new BizException(BizResultEnum.RETRY_DELAY_APP_SERVICE);
    }

    @Override
    public void saveAll(AccountDTO[] accountDtos) {
        this.sinkInterface.saveAll(accountDtos);
    }

    @Override
    public void saveAllList(List<AccountDTO> accountDTOList) {
        this.sinkInterface.saveAllList(accountDTOList);
    }

    @Override
    public void testParamsType(Object arg1, Object arg2, Object arg3) {
        this.sinkInterface.testParamsType(arg1,arg2,arg3);
    }
}
